//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;
using TWC = Telligent.Web.UI;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;
using StatusMessage = CommunityServer.ControlPanel.Controls.StatusMessage;

namespace CommunityServer.ControlPanel.Membership
{
	/// <summary>
	/// Summary description for UserEdit.
	/// </summary>
	public class UserEdit : BaseMembershipPage
	{

		#region Child Controls
		protected StatusMessage anonymousWarning;

		protected MPContent TaskRegion;
		protected TWC.TabbedPanes UserEditTabs;

		protected TimezoneDropDownList timezone;
		protected TextBox location;
		protected TextBox occupation;
		protected TextBox interests;
		protected TextBox webAddress;
		protected TextBox webLog;
		protected TextBox webGallery;
		protected TextBox signature;
		protected TextBox privateEmail;
		protected TextBox publicEmail;
		protected TextBox msnIM;
		protected TextBox aolIM;
		protected TextBox yahooIM;
		protected TextBox icq;
		protected TextBox avatarUrl;
		protected TextBox usernameEdit;
		protected YesNoRadioButtonList enableAvatar;
		protected RadioButtonList  hideReadPosts;
		protected YesNoRadioButtonList enableEmailTracking;
		protected YesNoRadioButtonList displayInMemberList;
		protected YesNoRadioButtonList enableHtmlEmail;
		protected YesNoRadioButtonList enableEmail;
		protected YesNoRadioButtonList enableInk;
		protected GenderRadioButtonList gender;
		protected LanguageDropDownList language;
		protected DateFormatDropDownList dateFormat;
		protected DatePickerToggle birthday;
		protected ResourceLinkButton updateButton;
		protected Button avatarUpdateButton;
		protected DateFilter defaultThreadView;
		protected RangeValidator signatureMaxLengthValidator;
		protected HtmlInputFile uploadedAvatar;
		protected HtmlAnchor changeUserName;
		protected HtmlAnchor changePassword;
		protected HtmlAnchor changeRoles;
		protected ModerationLevelDropDownList moderationLevel;
		protected YesNoRadioButtonList isAvatarApproved;
		protected YesNoRadioButtonList forceLogin;
		protected YesNoRadioButtonList isIgnored;
		protected AccountStatusDropDownList accountStatus;
		protected ThemeDropDownList theme;
		protected YesNoRadioButtonList enablePostPreviewPopup;
		protected HtmlTable userBanSection;
		protected UserBanDropDownList userBanPeriod;
		protected Label bannedUntilDate;
		protected HtmlTable userApprovalSection;
		protected YesNoRadioButtonList isApproved;
		protected Literal dateCreated;
		protected Literal lastLogin;
		protected Literal lastActivity;
		protected Literal userID;
		protected UserAvatar avatar;
		protected HyperLink UserMyForumsLink;
		protected HyperLink UserPrivateMessagesLink;
		protected TextBox dummyTotalPosts;
		protected UserBanReasonDropDownList userBanReason;
		protected YesNoRadioButtonList unlockUser;
		protected HtmlTableRow isLockedOutRow;
		protected HtmlTableRow EnablePostPreviewPopupRow;
		protected StatusMessage formStatus;
		protected YesNoRadioButtonList enableEmoticons;
		protected SortOrderDropDownList sortOrder;
		protected TextBox bio;
		protected TextBox CommonName;
		protected YesNoRadioButtonList enableDisplayNames;
		protected YesNoRadioButtonList enableUserSignatures;
		protected YesNoRadioButtonList enableUserAvtars;
		protected FontSizeDropDownList FontSize;
		protected DropDownList EditorList;
		protected YesNoRadioButtonList EnableCollapsingPanels;
		protected ControlPanelSelectedNavigation SelectedNavigation1;
		protected Modal Modal1;
		protected MPContent DescriptionRegion;
		protected MPContainer MPContainer;

        //EUPA Customization
        protected DropDownList SkillLevel;
        protected TextBox Address;
        protected TextBox Province;
        protected TextBox PostalCode;
        protected RadioButtonList Male;
        protected DatePicker BDay;
        protected Ultimate.Controls.MyTeams MyTeams1;



		protected Literal PanelDescription;
		#endregion

		override protected void OnInit(EventArgs e)
		{
			this.accountStatus.SelectedIndexChanged += new EventHandler(this.AccountStatus_Changed);
			this.updateButton.Click += new EventHandler(this.Update_Click);
			this.avatarUpdateButton.Click += new EventHandler(this.UpdateAvatar_Click);
			this.Load += new EventHandler(this.Page_Load);

			base.OnInit(e);
		}
		
		
		private void Page_Load(object sender, EventArgs e)
		{
			if ( !Page.IsPostBack ) 
			{
				Bind();
			}
		}

		public void Bind() 
		{
			CSContext csContext = CSContext.Current;

			User userToEdit = Users.GetUser(csContext.UserID, false, false);
			User currentUser = csContext.User;

			if( userToEdit.IsAdministrator && !currentUser.IsAdministrator)
				throw new CSException(CSExceptionType.ModerateAccessDenied );

			// Warn admins about editing the Anonymous user
			if (userToEdit.IsAnonymous)
			{
				anonymousWarning.ResourceName = "CP_UserEdit_AnonymousWarning";
				anonymousWarning.Success = false;
				anonymousWarning.Visible = true;
				// HACK: set this as license message to enable warning icon
				anonymousWarning.IsLicenseMessage = true;
			}

			// Save actual account status
			this.PrevAccountStatus = userToEdit.AccountStatus;

			// Set Title
			PanelDescription.Text = String.Format(ResourceManager.GetString("CP_UserEdit_TitleFormatString", controlPanelResourceFile), userToEdit.Username);

			signatureMaxLengthValidator.ErrorMessage = string.Format( Components.ResourceManager.GetString("EditProfile_SigMaxLength"), csContext.SiteSettings.UserSignatureMaxLength.ToString() );

			// Change username link
			changeUserName.InnerText = Components.ResourceManager.GetString("CP_UserEdit_ChangeUserName");
			changeUserName.HRef = String.Format("javascript:Telligent_Modal.Open('{0}', 500, 225, null);", Globals.GetSiteUrls().ControlPanelUserName(userToEdit.UserID));

			// Change password link
			changePassword.InnerText = Components.ResourceManager.GetString("CP_UserEdit_ChangePassword");
			changePassword.HRef = String.Format("javascript:Telligent_Modal.Open('{0}', 500, 175, null);", Globals.GetSiteUrls().ControlPanelUserPassword(userToEdit.UserID));

			// Add/Edit Roles link
			changeRoles.InnerText = Components.ResourceManager.GetString("CP_UserEdit_ChangeRoles");
			changeRoles.HRef = String.Format("javascript:Telligent_Modal.Open('{0}', 500, 350, null);", Globals.GetSiteUrls().ControlPanelUserRoles(userToEdit.UserID));

			// Set form to the current values of logged on user
			usernameEdit.Text = userToEdit.CommonNameOrUserName;
			usernameEdit.Enabled = csContext.SiteSettings.EnableUsernameChange;

			if ( timezone.Items.FindByValue( userToEdit.Profile.Timezone.ToString() ) != null) 
			{
				timezone.Items.FindByValue( userToEdit.Profile.Timezone.ToString() ).Selected = true;
			}

			// Find controls for Avatar/Post section
			//
			if ( (userToEdit.HasAvatar) && (userToEdit.EnableAvatar) && (userToEdit.IsAvatarApproved) ) 
			{
				avatar.User = userToEdit;
				avatar.Visible = true;
			}

			// If the admin has turned on post preview popups then we can turn it on
			if ( enablePostPreviewPopup != null ) 
			{
				if ( ForumConfiguration.Instance().EnablePostPreviewPopup ) 
				{
					enablePostPreviewPopup.SelectedValue = userToEdit.Profile.EnablePostPreviewPopup;
					enablePostPreviewPopup.Enabled = true;
				} 
				else 
				{
					EnablePostPreviewPopupRow.Visible = false;
				}
			}

			location.Text = Globals.HtmlDecode(userToEdit.Profile.Location);
			occupation.Text = Globals.HtmlDecode(userToEdit.Profile.Occupation);
			interests.Text = Globals.HtmlDecode(userToEdit.Profile.Interests);
			webAddress.Text = Globals.HtmlDecode(userToEdit.Profile.WebAddress);
			webLog.Text = Globals.HtmlDecode(userToEdit.Profile.WebLog);
			webGallery.Text = Globals.HtmlDecode(userToEdit.Profile.WebGallery);
			signature.Text = Globals.HtmlDecode(userToEdit.Profile.Signature);
			privateEmail.Text = userToEdit.Email;
			publicEmail.Text = Globals.HtmlDecode(userToEdit.Profile.PublicEmail);
			msnIM.Text = Globals.HtmlDecode(userToEdit.Profile.MsnIM);
			aolIM.Text = Globals.HtmlDecode(userToEdit.Profile.AolIM);
			yahooIM.Text = Globals.HtmlDecode(userToEdit.Profile.YahooIM);
			icq.Text = Globals.HtmlDecode(userToEdit.Profile.IcqIM);
			avatarUrl.Text = Globals.HtmlDecode(userToEdit.AvatarUrl);
			bio.Text = Globals.HtmlDecode(userToEdit.Profile.Bio);
			CommonName.Text = Globals.HtmlDecode(userToEdit.Profile.CommonName);
			enableDisplayNames.SelectedValue = userToEdit.EnableDisplayName;
			enableUserSignatures.SelectedValue = userToEdit.EnableUserSignatures;
			enableUserAvtars.SelectedValue = userToEdit.EnableUserAvtars;
			

			if ( birthday != null ) 
			{
				birthday.SelectedDate = userToEdit.Profile.BirthDate;
			}

			theme.SelectedValue = userToEdit.Theme;

			// Set the gender
			gender.Items.FindByValue( ((int) userToEdit.Profile.Gender).ToString() ).Selected = true;

			// Language Drop Down List
			if (language.Items.FindByValue( userToEdit.Profile.Language ) != null)
				language.Items.FindByValue( userToEdit.Profile.Language ).Selected = true;

			if (dateFormat.Items.FindByValue( userToEdit.Profile.DateFormat ) != null)
				dateFormat.Items.FindByValue( userToEdit.Profile.DateFormat ).Selected = true;

			enableAvatar.SelectedValue = userToEdit.EnableAvatar;
			enableEmailTracking.SelectedValue = userToEdit.EnableThreadTracking;
			enableHtmlEmail.SelectedValue = userToEdit.EnableHtmlEmail;
			enableEmail.SelectedValue = userToEdit.EnableEmail;
			enableInk.SelectedValue = userToEdit.EnableInk;
			displayInMemberList.SelectedValue = userToEdit.EnableDisplayInMemberList;
			FontSize.SelectedValue = userToEdit.Profile.FontSize.ToString();
			enableEmoticons.SelectedValue = userToEdit.Profile.EnableEmoticons;

			if (EnableCollapsingPanels.Items.FindByValue( userToEdit.EnableCollapsingPanels.ToString() ) != null)
				EnableCollapsingPanels.Items.FindByValue( userToEdit.EnableCollapsingPanels.ToString() ).Selected = true;
			
			if (sortOrder.Items.FindByValue( ((int)userToEdit.PostSortOrder).ToString() ) != null)
				sortOrder.Items.FindByValue( ((int)userToEdit.PostSortOrder).ToString() ).Selected = true;

			dateCreated.Text = csContext.User.GetTimezone( userToEdit.DateCreated ).ToString( csContext.User.Profile.DateFormat );
			lastLogin.Text = csContext.User.GetTimezone( userToEdit.LastLogin ).ToString( csContext.User.Profile.DateFormat );
			lastActivity.Text = csContext.User.GetTimezone( userToEdit.LastActivity ).ToString( csContext.User.Profile.DateFormat );

			// Editor
			foreach (SelectableEditor ei in csContext.Config.Editors)
				EditorList.Items.Add( new ListItem(ei.Name,ei.Name) );
			
			ListItem li = EditorList.Items.FindByValue(userToEdit.EditorType);
			if (li != null)
				li.Selected = true;

            //EUPA Cusomization
            if (SkillLevel != null)
                SkillLevel.SelectedValue = userToEdit.SkillLevel.ToString();

            if (Address != null)
                Address.Text = userToEdit.Address;

            if (Province != null)
                Province.Text = userToEdit.Province;

            if (PostalCode != null)
                PostalCode.Text = userToEdit.PostalCode;

            if (Male != null)
                Male.SelectedValue = userToEdit.Male.ToString();

            if (BDay != null)
                BDay.SelectedDate = userToEdit.BDay;

            MyTeams1.IUserID = userToEdit.UserID;

			BindExtendedUserControls(userToEdit);

			#region Administrator Area

			userID.Text = userToEdit.UserID.ToString();
            
			if (userToEdit.Member != null) 
			{
				unlockUser.SelectedValue = !userToEdit.Member.IsLockedOut;
				isLockedOutRow.Visible = userToEdit.Member.IsLockedOut;
			}

			moderationLevel.SelectedValue = userToEdit.ModerationLevel;
			dummyTotalPosts.Text = userToEdit.DummyTotalPosts.ToString();

			forceLogin.SelectedValue = userToEdit.ForceLogin;

			isAvatarApproved.SelectedValue = userToEdit.IsAvatarApproved;

			isIgnored.SelectedValue = userToEdit.IsIgnored;
                
			// Account Status
			accountStatus.DataBind();
			accountStatus.SelectedValue = userToEdit.AccountStatus;

			// User Banning
			bool isBanTabVisible = (userToEdit.AccountStatus == UserAccountStatus.Banned) ? true : false;
			UserEditTabs.Panes[5].Visible = isBanTabVisible;
			userBanSection.Visible = isBanTabVisible;

			bannedUntilDate.Text = this.GetBannedDateValue(ref userToEdit);
			// LN: 5/21/04 : Added to signal admin that a user's ban has expired.
			if (userToEdit.IsBanned && DateTime.Now > userToEdit.BannedUntil) 
			{
				bannedUntilDate.Text += Components.ResourceManager.GetString("EditProfile_BanExpired");
				bannedUntilDate.ForeColor = Color.Red;
			}
			userBanPeriod.SelectedValue = this.GetRemainingBannedDays(userToEdit.BannedUntil);
			userBanReason.SelectedValue = userToEdit.BanReason;
                
			// User Approval
			userApprovalSection.Visible = (userToEdit.AccountStatus == UserAccountStatus.ApprovalPending) ? true : false;                                        
			isApproved.SelectedValue = (userToEdit.AccountStatus == UserAccountStatus.Approved) ? true : false;

			#endregion

			avatarUpdateButton.Text = ResourceManager.GetString("Update");

			formStatus.Visible = false;
		}



		#region Event Handlers
		public void AccountStatus_Changed(Object sender, EventArgs e) 
		{

			User userToEdit = Users.GetUser(CSContext.Current.UserID, false, false);

			// User Approval
			if (userApprovalSection != null) 
			{

				// show/hide the "Approve User" section
				//
				switch (userToEdit.AccountStatus) 
				{
					case (UserAccountStatus.ApprovalPending):
						userApprovalSection.Visible = true;
						break;

					default:
						userApprovalSection.Visible = false;
						break;
				}
			}

			// User Banning (keep this code after Approval code)
			if (userBanSection != null) 
			{

				bool isBanTabVisible = (accountStatus.SelectedValue == UserAccountStatus.Banned) ? true : false;
				UserEditTabs.Panes[5].Visible = isBanTabVisible;
				userBanSection.Visible = isBanTabVisible;
			}

		}

		public void UpdateAvatar_Click (Object sender, EventArgs e) 
		{
			try 
			{
				UpdateAvatar(  CSContext.Current.UserID );
			} 
			catch 
			{
				throw new CSException(CSExceptionType.UnknownError);
			}
			Update_Click(sender, e);
		}

		public void Update_Click (Object sender, EventArgs e) 
		{
			if ( AreValuesValid ) 
			{
				User userToEdit = Users.GetUserWithWriteableProfile(CSContext.Current.UserID, null,false);

				if (Update( userToEdit ))
				{
					formStatus.Success = true;
					formStatus.Visible = true;
					formStatus.ResourceName = "CP_Config_OK";
				}
					
			}
		}

		#endregion

		#region Command Implementors
		protected virtual bool Update( User userToEdit ) 
		{
			bool hasBanned = false;
			bool hasBanBeenUsed = false;
			bool postModerationChanged = false; 
			bool hasModerated = false;
			bool hasIgnored = false;
			bool hasIgnoredChanged = false;

			// Get the updated values from the form
			//
			CSContext cntx = CSContext.Current;
			if (cntx.SiteSettings.EnableUsernameChange)
				userToEdit.Username = usernameEdit.Text;

			// Update gender?
			if (cntx.SiteSettings.AllowGender) 
			{
				userToEdit.Profile.Gender = (Gender) int.Parse(gender.SelectedItem.Value);
			}

			userToEdit.Profile.Timezone = double.Parse(timezone.SelectedItem.Value);
			userToEdit.Profile.Location = location.Text;
			userToEdit.Profile.Occupation = occupation.Text;
			userToEdit.Profile.Interests = interests.Text;
			userToEdit.Profile.WebAddress = webAddress.Text;
			userToEdit.Profile.WebLog = webLog.Text;
			userToEdit.Profile.WebGallery = webGallery.Text;
			userToEdit.Profile.Bio = bio.Text;
			userToEdit.Profile.CommonName = CommonName.Text;
			userToEdit.EnableDisplayName = enableDisplayNames.SelectedValue;
			userToEdit.EnableUserAvtars = enableUserAvtars.SelectedValue;
			userToEdit.EnableUserSignatures = enableUserSignatures.SelectedValue;


			if( cntx.SiteSettings.EnableCensorship ) 
			{
				userToEdit.Profile.Signature = Transforms.CensorPost( signature.Text );
			} 
			else 
			{
				userToEdit.Profile.Signature = signature.Text;
			}
			
			userToEdit.Email = privateEmail.Text;
			userToEdit.Profile.PublicEmail = publicEmail.Text;
			userToEdit.Profile.MsnIM = msnIM.Text;
			userToEdit.Profile.AolIM = aolIM.Text;
			userToEdit.Profile.YahooIM = yahooIM.Text;
			userToEdit.Profile.IcqIM = icq.Text;
			userToEdit.AvatarUrl = avatarUrl.Text;
			userToEdit.Profile.DateFormat = dateFormat.SelectedItem.Value;
			userToEdit.EnableAvatar = enableAvatar.SelectedValue;
			userToEdit.Profile.EnableEmoticons = enableEmoticons.SelectedValue;

			if (int.Parse(sortOrder.SelectedItem.Value) == 1)
				userToEdit.PostSortOrder = SortOrder.Descending;
			else
				userToEdit.PostSortOrder = SortOrder.Ascending;
			
			userToEdit.EnableThreadTracking = enableEmailTracking.SelectedValue;
			userToEdit.EnableEmail = enableEmail.SelectedValue;
			if( !cntx.SiteSettings.EnableEmail ) 
			{
				userToEdit.EnableThreadTracking = false;
				userToEdit.EnableEmail = false;
			}
			userToEdit.EnableInk = enableInk.SelectedValue;
			userToEdit.EnableDisplayInMemberList = displayInMemberList.SelectedValue;
			userToEdit.EnableHtmlEmail = enableHtmlEmail.SelectedValue;

			userToEdit.Profile.Language = language.SelectedItem.Value;

			if (enablePostPreviewPopup != null && ForumConfiguration.Instance().EnablePostPreviewPopup)  
			{  				
				userToEdit.Profile.EnablePostPreviewPopup = enablePostPreviewPopup.SelectedValue;
			}

			userToEdit.Profile.FontSize = int.Parse(FontSize.SelectedValue);
			userToEdit.EditorType = EditorList.SelectedValue;
			userToEdit.EnableCollapsingPanels = bool.Parse( EnableCollapsingPanels.SelectedItem.Value );
       
			if (birthday != null)
				userToEdit.Profile.BirthDate = birthday.SelectedDate;

			userToEdit.Theme = theme.SelectedValue;
            
			// Detect if moderationlevel has changed: moderated <=> unmoderated
			//
			if (userToEdit.ModerationLevel != moderationLevel.SelectedValue) 
			{
				if (moderationLevel.SelectedValue == ModerationLevel.Moderated && 
					userToEdit.ModerationLevel == ModerationLevel.Unmoderated) 
				{
					postModerationChanged = true;
					hasModerated = true;
				}
				if (moderationLevel.SelectedValue == ModerationLevel.Unmoderated &&
					userToEdit.ModerationLevel == ModerationLevel.Moderated) 
				{ 
					postModerationChanged = true;
					hasModerated = false;
				}
			}

			userToEdit.ModerationLevel = moderationLevel.SelectedValue;
        
			// Detect if selected user has been banned
			//
			if (userToEdit.IsBanned && accountStatus.SelectedValue == UserAccountStatus.Approved) 
			{
				hasBanned = false;
				hasBanBeenUsed = true;
			}             
			if (!userToEdit.IsBanned && accountStatus.SelectedValue == UserAccountStatus.Banned) 
			{ 
				hasBanned = true;
				hasBanBeenUsed = true;
			}

			userToEdit.AccountStatus = accountStatus.SelectedValue;
			userToEdit.IsAvatarApproved = isAvatarApproved.SelectedValue;
			userToEdit.ForceLogin = forceLogin.SelectedValue;
			
			if (userToEdit.IsIgnored != isIgnored.SelectedValue)
			{
				userToEdit.IsIgnored = isIgnored.SelectedValue;
				hasIgnoredChanged = true;
			}
			if (hasIgnoredChanged && isIgnored.SelectedValue == true)
			{
				hasIgnored = true;
			}
			
			try 
			{
				userToEdit.DummyTotalPosts = Int32.Parse( dummyTotalPosts.Text.Trim() );
			} 
			catch 
			{ 
				userToEdit.DummyTotalPosts = userToEdit.TotalPosts;
			}

			// User Banning
			if (accountStatus.SelectedValue == UserAccountStatus.Banned)
				userToEdit.BannedUntil = DateTime.Now.AddDays((int) userBanPeriod.SelectedValue);
			else
				userToEdit.BannedUntil = DateTime.Now;
			userToEdit.BanReason = userBanReason.SelectedValue;
            
			// User Approval
			if (userApprovalSection.Visible == true && 
				accountStatus.SelectedValue == UserAccountStatus.ApprovalPending) 
			{

				if (isApproved.SelectedValue == true) 
				{
					// Change status to Approved
					userToEdit.AccountStatus = UserAccountStatus.Approved;
				}

				if (isApproved.SelectedValue == false) 
				{
					// Change status to Disapproved
					userToEdit.AccountStatus = UserAccountStatus.Disapproved;
				}
			}

            //EUPA CUstomization
            if (SkillLevel != null)
                userToEdit.SkillLevel = Convert.ToInt32(SkillLevel.SelectedValue);

            if (Address != null)
                userToEdit.Address = Address.Text;

            if (Province != null)
                userToEdit.Province = Province.Text;

            if (PostalCode != null)
                userToEdit.PostalCode = PostalCode.Text;

            if (Male != null)
                userToEdit.Male = Convert.ToBoolean(Male.SelectedValue);

            if (BDay != null)
                userToEdit.BDay = BDay.SelectedDate;


			SetExtendedUserData(userToEdit);

			#region TODO
			/* TODO
			// Does the user have a user uploaded avatar?
			//
			if (uploadedAvatar.PostedFile.ContentLength > 0) {
				Stream fs = uploadedAvatar.PostedFile.InputStream;

				// Is the avatar an allowed size?
				//
				if (PostedFile.ContentLength > CSContext.Current.SiteSettings.AvatarMaxSize) {
				}

				// Is the avatar within the allowed dimensions?
				//
				fs = ForumImage.ResizeImage(fs, CSContext.Current.SiteSettings.AvatarHeight, CSContext.Current.SiteSettings.AvatarWidth);

				// Add the avatar to the database
				//
				ForumImage.AddUserAvatar(fs, userToEdit.Username);

				// Does the new avatar require approval
				//
				if (CSContext.Current.SiteSettings.EnableAvatarRequireApproval)
					userToEdit.IsAvatarApproved = false;
				else
					userToEdit.IsAvatarApproved = true;

				userToEdit.AvatarUrl = Globals.GetSiteUrls().ForumImage(userToEdit.Username);
			} */
			#endregion

			// Update the user
			try 
			{
				Users.UpdateUser(userToEdit);

			}
			catch (CSException ex) 
			{
				// Check to see if the MemberRole component threw a duplicate email exception. If so we want to handle it gracefully.
				if (ex.CreateUserStatus == CreateUserStatus.DuplicateEmailAddress)
				{
					// Notify that update was not successful because of duplicate email
					formStatus.Visible = true;
					formStatus.Success = false;
					formStatus.ResourceName = "EditProfile_DuplicateEmail";
					return false;
				}

				throw;
			}


			// Log Audit: ban/unban, moderate/unmoderate ignore/unignore
			//
			Audit.SaveUserAuditEvent( ModerateUserSetting.UserEdited, userToEdit, cntx.User.UserID ); 
           
			if (hasBanBeenUsed) 
			{ 
				if (hasBanned)
					Audit.SaveUserAuditEvent( ModerateUserSetting.UserBanned, userToEdit, cntx.User.UserID );
				else
					Audit.SaveUserAuditEvent( ModerateUserSetting.UserUnbanned, userToEdit, cntx.User.UserID );
			}
			if (postModerationChanged) 
			{ 
				if (hasModerated)
					Audit.SaveUserAuditEvent( ModerateUserSetting.UserModerated, userToEdit, cntx.User.UserID );
				else
					Audit.SaveUserAuditEvent( ModerateUserSetting.UserUnmoderated, userToEdit, cntx.User.UserID );
			}
			if (hasIgnoredChanged)
			{
				if (hasIgnored)
				{
					Audit.SaveUserAuditEvent(ModerateUserSetting.UserIgnored, userToEdit, cntx.User.UserID );
				}
				else
				{
					Audit.SaveUserAuditEvent(ModerateUserSetting.UserUnignored, userToEdit, cntx.User.UserID );
				}
			}
            
			// Unlock user profile
			//
			if (userToEdit.Member != null && userToEdit.Member.IsLockedOut && 
				unlockUser.SelectedValue == true) 
			{ 
				userToEdit.Member.UnlockUser();
			}

			// Send notification emails after the update took place
			//

			// User Approval
			if( this.PrevAccountStatus == UserAccountStatus.ApprovalPending &&
				userToEdit.AccountStatus == UserAccountStatus.Approved )  
			{

				Emails.UserAccountApproved(userToEdit);
			}

			if( this.PrevAccountStatus == UserAccountStatus.ApprovalPending &&
				userToEdit.AccountStatus == UserAccountStatus.Disapproved ) 
			{

				Emails.UserAccountRejected(userToEdit, cntx.User);
			}

         
			// Notify the End of Update
			return true;

			//throw new CSException(CSExceptionType.UserProfileUpdated);

		}

		protected virtual void UpdateAvatar( Int32 userID ) 
		{
			Resources.UpdateAvatar( userID, uploadedAvatar.PostedFile.InputStream );
			avatarUrl.Text = "users/avatar.aspx?userid=" + userID.ToString();
		}

		protected virtual Boolean AreValuesValid 
		{
			get 
			{
				// Check the max length on the signature
				//
				if (signature.Text.ToString().Length > CSContext.Current.SiteSettings.UserSignatureMaxLength) 
				{
					signatureMaxLengthValidator.IsValid = false;
					return false;
				} 
				else 
				{
					signatureMaxLengthValidator.IsValid = true;
					return true;
				}
			}
		}
		#endregion

		#region Helper Properties & Methods

		[
			DefaultValue( UserAccountStatus.Approved ),
		]
		public virtual UserAccountStatus PrevAccountStatus 
		{
			get 
			{
				Object state = ViewState["PrevAccountStatus"];
				if ( state != null ) 
				{
					return (UserAccountStatus)state;
				}
				return UserAccountStatus.Approved;
			}
			set 
			{
				ViewState["PrevAccountStatus"] = value;
			}
		}

		private UserBanPeriod GetRemainingBannedDays(DateTime bannedUntil) 
		{

			UserBanPeriod daysNo = UserBanPeriod.Permanent;
			if(DateTime.Now > bannedUntil)
				return daysNo;

			int diff = ((TimeSpan) (bannedUntil - DateTime.Now)).Days;
			if(diff <= (int) UserBanPeriod.OneDay) 
			{
				daysNo = UserBanPeriod.OneDay;
			}
			else if(diff > (int) UserBanPeriod.OneDay && diff <= (int) UserBanPeriod.ThreeDays) 
			{
				daysNo = UserBanPeriod.ThreeDays;
			}
			else if(diff > (int) UserBanPeriod.ThreeDays && diff <= (int) UserBanPeriod.FiveDays) 
			{
				daysNo = UserBanPeriod.FiveDays;
			}
			else if(diff > (int) UserBanPeriod.FiveDays && diff <= (int) UserBanPeriod.OneWeek) 
			{
				daysNo = UserBanPeriod.OneWeek;
			}
			else if(diff > (int) UserBanPeriod.OneWeek && diff <= (int) UserBanPeriod.TwoWeeks) 
			{
				daysNo = UserBanPeriod.TwoWeeks;
			}
			else if(diff > (int) UserBanPeriod.TwoWeeks && diff <= (int) UserBanPeriod.OneMonth) 
			{
				daysNo = UserBanPeriod.OneMonth;
			}
			else if(diff > (int) UserBanPeriod.OneMonth) 
			{
				daysNo = UserBanPeriod.Permanent;
			}

			return daysNo;
		}

		/// <summary>
		/// Format banned date.
		/// </summary>
		private string GetBannedDateValue(ref User userToEdit) 
		{
			if (userToEdit != null && userToEdit.IsBanned) 
			{
				CSContext cntx = CSContext.Current;
				string dateFormat = cntx.User.Profile.DateFormat;
				string timeFormat = cntx.SiteSettings.TimeFormat;

				return userToEdit.BannedUntil.ToString( dateFormat + " " + timeFormat );

				/* 
				 * Don't convert to GMT anymore.
				 * 
				return Formatter.FormatDate(userToEdit.BannedUntil, true);
				*/
			} 
			else
				return ResourceManager.GetString("NotSet");
		}

		private void BindExtendedUserControls(User userToEdit)
		{
			foreach (string controlName in ExtendedUserData.Fields)
			{
				Control c  = TaskRegion.FindControl(controlName);
				if (c != null)
				{
					string value = userToEdit.GetExtendedAttribute(c.ID);

					if (c is TextBox)
						((TextBox)c).Text = value;
					else if ((c is CheckBox) && (value != string.Empty))
						((CheckBox)c).Checked = bool.Parse(value);
					else if ((c is ListControl) && (((ListControl)c).Items.FindByValue(value) != null))
						((ListControl)c).SelectedValue = value;
				}
			}
		}

		private void InitializeComponent()
		{
		
		}

		private void SetExtendedUserData(User userToEdit)
		{
			foreach (string controlName in ExtendedUserData.Fields)
			{
				Control c  = TaskRegion.FindControl(controlName);
				if (c != null)
				{
					string value = null;

					if (c is TextBox)
						value = ((TextBox)c).Text;
					else if (c is ListControl)
						value = ((ListControl)c).SelectedValue;
					else if (c is CheckBox)
						value = ((CheckBox)c).Checked.ToString();

					if (value != null)
						userToEdit.SetExtendedAttribute(c.ID, value);
				}
			}
		}
		#endregion

	}
}
